package com.zhkj.crawl.utils;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * 计算方法执行时间
 */
public class TimeDistance {
	private final LinkedList<String> queue;
	private final long start;
	private long last;

	public TimeDistance(){
		last = start = System.currentTimeMillis();
		queue = new LinkedList<>();
	}

	public long distance(){
		long now = System.currentTimeMillis();
		long distance = now - last;
		last = now;
		return distance;
	}

	public void dot(){
		queue.add(calculate(distance()));
	}

	private String calculate(long distance) {
		long sec = distance / 1000;
		String ret = null;
		if(sec == 0){
			ret = distance + "ms";
		}else if(sec < 60){
			ret = sec + "s";
		}else if(sec < 3600){
			ret = String.format("%sm%ss", sec / 60, sec % 60);
		}else {
			ret = String.format("%sh%sm%ss", sec / 3600, (sec % 3600 / 60), (sec % 3600 % 60));
		}
		return ret;
	}

	public String total(){
		long distance = System.currentTimeMillis() - start;
		return calculate(distance);
	}

	public String pop(){
		if(!queue.isEmpty()){
			return queue.pop();
		}
		return "";
	}

	public boolean hasNext(){
		return !queue.isEmpty();
	}

	public static void main(String[] args) throws InterruptedException {
		TimeDistance distance = new TimeDistance();
		TimeUnit.MILLISECONDS.sleep(300);
		distance.dot();
		TimeUnit.SECONDS.sleep(5);
		distance.dot();
		TimeUnit.SECONDS.sleep(4);
		distance.dot();

		while (distance.hasNext()){
			System.out.println(distance.pop());
		}
		System.out.println(distance.total());
	}

}
